<?php
function temp_sort($a, $b)
{
    return ($a->goldCount > $b->goldCount) ? -1 : 1;
}
class UserController extends Controller
{
    public function actionApiTest()
    {
        $this->renderPartial('apiTest', array(
        ));
    }

    public function actionDiLogin()
    {
        return null;
    }
    public function actionDiSubmitRecord()
    {
        return null;
    }

    public function actionIndex()
    {
        $this->render('index', array(
        ));
    }

    public function actionLevelInfo()
    {
        /* 		$d = self::genString();
                parent::llog($d.$this->aa,"Test.Index");
                // renders the view file 'protected/views/site/index.php'
                // using the default layout 'protected/views/layouts/main.php'
                $readJsonPost = Trans::readJsonPost();
                $posttest = $_POST;
                $this->renderPartial('json', array(
                    'jsonArr'=>array(
                        'sessionId' => 122344,
                        'SMSFormat' => 'agasfgg',
                        'readJsonPost'=>$readJsonPost,
                        'posttest' =>$posttest
                        )
                    )); */
        $jsonObj = Trans::readJsonPost();

        $result = null;
        parent::llog(json_encode($jsonObj), "Filters.token.index.post");
//        $criteria = new CDbCriteria;
//        $criteria->limit = 60;
//        $criteria->offset = 0;
//        $u = User::model()->findByPk(92);
//        $modelList = User::model()->findAll($criteria);
//        //var_dump($modelList);
        $criteria = new CDbCriteria;
        $criteria->addCondition("id> :id");
        $criteria->params[':id']=221;
        $modelList = User::model()->findAll($criteria);
        $devices = [];
        foreach($modelList as $model)
        {
            $devices[] = $model->device;
        }
        $allStage = new stdClass();
        for($i=1;$i<=38;$i++)
        {
            $stage = "stage".$i;
            $allKey = UserService::getInstance()->getTemp($stage);
            $filterKey = [];
            foreach($allKey as $key)
            {
                if(in_array($key,$devices))
                {
                    $filterKey[] = $key;
                }
            }
            $allStage->$stage = new stdClass();
            $level2 = 0;
            $level3 = 0;
            $level4 = 0;
            foreach($filterKey as $fk)
            {
                $level = UserService::getInstance()->getUserStageLevel($fk, $stage);
                if($level==2)
                {
                    $level2++;
                }elseif($level==3)
                {
                    $level3++;
                }elseif($level==4)
                {
                    $level4++;
                }
            }
            $allStage->$stage->level2 = $level2;
            $allStage->$stage->level3 = $level3;
            $allStage->$stage->level4 = $level4;
        }

//        foreach ($modelList as $model) {
//            $device  = $model->device;
//            $goldCount = 0;
//            for($i=1;$i<=54;$i++)
//            {
//                $stage = "stage".$i;
//                $level = UserService::getInstance()->getUserStageLevel($device, $stage);
//                if($level==4)
//                {
//                    $goldCount++;
//                }
//            }
//            $obj = new stdClass();
//            $obj->device = $device;
//            $obj->goldCount = $goldCount;
//            $result[] = $obj;
//        }
//        usort($result, "temp_sort");
//        foreach ($modelList as $model) {
//            $temp = $model->higest_score;
//            $model->final_stage = 38;
//            $temp->stage38 = 0;
//            $model->higest_score = json_encode($temp);
//            $model->save();
//        }

        $this->renderPartial('jsonDev', array(
            'jsonArr' => $allStage,
            'postdata' => Translate::tran("help", "cn")
        ));
    }


    public function actionRequestToken()
    {
        $jsonObj = Trans::readJsonPost();

        if (!isset($jsonObj->deviceCode)) {
            $result = array("status" => 0, "msg" => "deviceCode cann't be empty");
        } else {
            $rnum = $this->randStr(6, 'NUMBER');
            if ((int)$rnum < 900000) $rnum = (int)$rnum + 100000;
            UserService::getInstance()->addToken($rnum, $jsonObj->deviceCode);
            $result = array("status" => 1, "token" => $rnum);
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }



    public function actionRequestUserInfo()
    {
        //{"deviceCode":"Axkas-192365-eeaeee"}
        parent::llog("begin", "User.Request.Begin");
        $result;
        $jsonObj = Trans::readJsonPost();
        parent::llog(json_encode($jsonObj), "User.Request.PostData");
        if (!isset($jsonObj->deviceCode)) {
            $result = array("status" => 0, "msg" => "deviceCode can not be empty");
        } else {
            try {
                $User = UserService::getInstance()->getCacheU($jsonObj->deviceCode);
                $fromCache = false;
                $uProperty;
                if (!isset($User)) {
                    $User = User::model()->find('device=:device', array(':device' => $jsonObj->deviceCode));
                } else {
                    $fromCache = true;
                }
                if (is_null($User)) {
                    date_default_timezone_set('UTC');
                    $User = new User();
                    $User->device = $jsonObj->deviceCode;
                    $User->user_name = Config::$default_name[array_rand(Config::$default_name, 1)];
                    $User->rank = 0;
                    $User->deja_id = -1;
                    $User->final_stage = 1;
                    $User->create_time = date('Y-m-d H:i:s', time());
                    $User->higest_score = json_encode(array("stage1"=>0));
                    $User->save();
                }
                if ($fromCache) {
                    parent::llog("from cache", "User.PP");
                    $uProperty = $User;
                    Trans::sendUrlGet("http://127.0.0.1:8081/g_shooter/User/DiLogin?momoid=".$uProperty->id);
                } else {
                    parent::llog("from database", "User.PP");
                    $uProperty = $User->attributes;
                    $uProperty["higest_score"] = json_decode($uProperty["higest_score"]);
                    Trans::sendUrlGet("http://127.0.0.1:8081/g_shooter/User/DiLogin?momoid=".$uProperty["id"]);
                }
                array_walk_recursive($uProperty, function (&$item, $key) {
                    if (is_numeric($item)) {
                        $item = (int)$item;
                    }
                });

                UserService::getInstance()->addDeviceUKey($jsonObj->deviceCode, json_encode($uProperty));
                $result = array("status" => 1, "user" => $uProperty);
//                if (isset($jsonObj->phoneNumber) && (!isset($User->deja_id) || $User->deja_id == -1)) {
//                    $sendSMSUrl = trim(Config::$public_apis['requestVcode'], '/');
//                    $postdata = json_encode(array("phoneNumber" => $jsonObj->phoneNumber));
//                    parent::llog($postdata, "User.RequestVaild.deja.Postdata");
//                    parent::llog($sendSMSUrl, "User.RequestVaild.deja.PostUrl");
//                    $resStr = Trans::sendUrlPostJson($sendSMSUrl, $postdata);
//                    parent::llog($resStr, "User.RequestVaild.deja.Returndata");
//                    if (!empty($resStr)) {
//                        $resStr = json_decode($resStr);
//                        if (isset($resStr->sessionId) && isset($resStr->SMSFormat)) {
//                            parent::llog($resStr->sessionId, "User.Request");
//                            $result = array("status" => 2, "user" => $uProperty, "sessionId" => $resStr->sessionId, "SMSFormat" => $resStr->SMSFormat);
//                        }
//                    }
//                }



            } catch (Exception $e) {
                $result = array("status" => 0, "msg" => "error");
            }
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }
    public function actionSuperBindDejaData()
    {
        //{"deviceCode":"AAAAA888TT8","dejaId":10002}
        $jsonObj = Trans::readJsonPost();
        $getTokenUrl = trim(Config::$public_apis['askCode'], '/').$jsonObj->dejaId;
        $resStr = Trans::sendUrlGet($getTokenUrl);
        if(isset($resStr))
        {
            $resStr = json_decode($resStr);
            $code = $resStr->code;
            $getTokenUrl = trim(Config::$public_apis['gettoken'], '/');
            $postData = arrayToKV(array("grant_type" => "authorization_code", "code" => $code, "client_id" => Config::$client_id, "client_secret" => Config::$client_secret));
            parent::llog($postData, "User.getToken.PostData");
            $resStr = Trans::sendUrlPostKV($getTokenUrl, $postData);
            parent::llog(json_encode($resStr), "User.getToken.ReturnData");
            if (!empty($resStr)) {
                $resStr = json_decode($resStr);
                if (isset($resStr->error)) {
                    $result = array("status" => 0, "msg" => $resStr->error_description);
                } else {
                    $access_token = $resStr->access_token;
                    $refresh_token = $resStr->refresh_token;
                    UserService::getInstance()->setDeviceToken($jsonObj->deviceCode, $access_token);
                    UserService::getInstance()->setDeviceRefreshToken($jsonObj->deviceCode, $refresh_token);
                    $meUrl = trim(Config::$public_apis['me'], '/');
                    $postDataT = array("access_token" => $access_token);
                    $resStrT = UserService::getInstance()->requestDejaApi($meUrl, $postDataT, $jsonObj->deviceCode);
                    parent::llog(json_encode($resStrT), "User.me.ReturnData");
                    if (!empty($resStrT)) {
                        if (isset($resStrT->error)) {
                            $result = array("status" => 0, "msg" => $resStrT->error_description);
                        } else {
                            $u = UserService::getInstance()->findByDevice($jsonObj->deviceCode);
                            if (isset($u)) {
                                $u->deja_id = $resStrT->userId;
                                $u->user_name = $resStrT->name;
                                UserService::getInstance()->addDejaDeviceKey($u->deja_id, $jsonObj->deviceCode);
                                $modelArr = $u->attributes;
                                $u->save();
                                array_walk_recursive($modelArr, function (&$item, $key) {
                                    if (is_numeric($item)) {
                                        $item = (int)$item;
                                    }
                                });
                                UserService::getInstance()->updateDeviceUKey($jsonObj->deviceCode, json_encode($modelArr));
                                $result = array("status" => 1, "user" => $modelArr);
                            } else {
                                $result = array("status" => 0, "msg" => "Device not found");
                            }
                        }
                    } else {
                        $result = array("status" => 0, "msg" => "error");
                    }
                }
            }
        }

    }


    public function actionBindDejaData()
    {
        //{"deviceCode":"AAAAA888TT8","code":"akdjakjgadawioeqieuigigiqiouqieq"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $size = 128;
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->deviceCode) && isset($jsonObj->code)) {
            $getTokenUrl = trim(Config::$public_apis['gettoken'], '/');
            $postData = arrayToKV(array("grant_type" => "authorization_code", "code" => $jsonObj->code, "client_id" => Config::$client_id, "client_secret" => Config::$client_secret));
            parent::llog($postData, "User.getToken.PostData");
            $resStr = Trans::sendUrlPostKV($getTokenUrl, $postData);
            parent::llog(json_encode($resStr), "User.getToken.ReturnData");
            if (!empty($resStr)) {
                $resStr = json_decode($resStr);
                if (isset($resStr->error)) {
                    $result = array("status" => 0, "msg" => $resStr->error_description);
                } else {
                    $access_token = $resStr->access_token;
                    $refresh_token = $resStr->refresh_token;
                    UserService::getInstance()->setDeviceToken($jsonObj->deviceCode, $access_token);
                    UserService::getInstance()->setDeviceRefreshToken($jsonObj->deviceCode, $refresh_token);
                    $meUrl = trim(Config::$public_apis['me'], '/');
                    $postDataT = array("access_token" => $access_token);
                    $resStrT = UserService::getInstance()->requestDejaApi($meUrl, $postDataT, $jsonObj->deviceCode);
                    parent::llog(json_encode($resStrT), "User.me.ReturnData");
                    if (!empty($resStrT)) {
                        if (isset($resStrT->error)) {
                            $result = array("status" => 0, "msg" => $resStrT->error_description);
                        } else {
                            $u = UserService::getInstance()->findByDevice($jsonObj->deviceCode);
                            if (isset($u)) {
                                $u->deja_id = $resStrT->userId;
                                $u->user_name = $resStrT->name;
                                UserService::getInstance()->addDejaDeviceKey($u->deja_id, $jsonObj->deviceCode);
                                $modelArr = $u->attributes;
                                $u->save();
                                array_walk_recursive($modelArr, function (&$item, $key) {
                                    if (is_numeric($item)) {
                                        $item = (int)$item;
                                    }
                                });
                                UserService::getInstance()->updateDeviceUKey($jsonObj->deviceCode, json_encode($modelArr));
                                $result = array("status" => 1, "user" => $modelArr);
                            } else {
                                $result = array("status" => 0, "msg" => "Device not found");
                            }
                        }
                    } else {
                        $result = array("status" => 0, "msg" => "error");
                    }
                }
            } else {
                $result = array("status" => 0, "msg" => "error");
            }
        } else {
            $result = array("status" => 0, "msg" => "need deviceCode,code,state");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


//    public function actionValidCode()
//    {
//        //{"deviceCode":"Axkas-192365-eeaeee","phoneNumber":"98083491","sessionId":123,"validCode":123}
//        $result;
//        $jsonObj = Trans::readJsonPost();
//        parent::llog(json_encode($jsonObj), "User.VaildCode.PostData");
//        $size = 128;
//        if (isset($jsonObj->size)) {
//            $size = $jsonObj->size;
//        }
//        if (isset($jsonObj->deviceCode) && isset($jsonObj->phoneNumber) && isset($jsonObj->sessionId) && isset($jsonObj->validCode)) {
//            try {
//                $User = User::model()->find('device=:device', array(':device' => $jsonObj->deviceCode));
//                if (is_null($User)) {
//                    throw new Exception('device no exist');
//                }
//                $sendSMSUrl = trim(Config::$public_apis['verifyPhoneNumber'], '/');
//                $postdata = json_encode(array("phoneNumber" => $jsonObj->phoneNumber, "sessionId" => $jsonObj->sessionId, "vcode" => $jsonObj->validCode));
//                parent::llog($postdata, "User.VaildCode.deja.Postdata");
//                $resStr = Trans::sendUrlPostKV($sendSMSUrl, $postdata);
//                parent::llog($resStr, "User.VaildCode.deja.Returndata");
//                if (!empty($resStr)) {
//                    $resStr = json_decode($resStr);
//                    $User->deja_id = $resStr->userId;
//                    $dejaM = UserService::getInstance()->getDejaModel($resStr->userId, "", $size);
//                    if (isset($dejaM)) {
//                        $User->user_name = $dejaM->name;
//                    }
//                    UserService::getInstance()->addDejaDeviceKey($User->deja_id, $jsonObj->deviceCode);
//                    $User->save();
//                    $modelArr = $User->attributes;
//                    array_walk_recursive($modelArr, function (&$item, $key) {
//                        if (is_numeric($item)) {
//                            $item = (int)$item;
//                        }
//                    });
//                    UserService::getInstance()->updateDeviceUKey($jsonObj->deviceCode, json_encode($modelArr));
//                    $result = array("status" => 1, "user" => $modelArr);
//                } else {
//                    $result = array("status" => 0, "msg" => "valid code error");
//                }
//
//            } catch (Exception $e) {
//                $result = array("status" => 0, "msg" => $e->getMessage());
//            }
//        } else {
//            $result = array("status" => 0, "msg" => "need deviceCode,phoneNumber,sessionId,validCode");
//        }
//        $this->renderPartial('json', array(
//            'jsonArr' => $result,
//            'postdata' => $jsonObj,
//        ));
//    }

    public function actionRequestSelfDejaData()
    {
        //{"dejaId":100032,"size":64,"deviceCode":"AAASASSS"}
        $result;
        $size = 128;
        $jsonObj = Trans::readJsonPost();
        $faceId = "";
        if (isset($jsonObj->faceId)) {
            $faceId = $jsonObj->faceId;
        }
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (!isset($jsonObj->deviceCode)) {
            $result = array("status" => 0, "msg" => "deviceCode is require");
        } else {
            parent::llog(json_encode($jsonObj), "User.RequestSelfDejaData.PostData");
            $u = UserService::getInstance()->getUserByDevice($jsonObj->deviceCode);
            if (isset($u)) {
                if ($u->deja_id == -1) {
                    $dejaM = UserService::getInstance()->getDefaultDejaModel($u->deja_id, $jsonObj->deviceCode, $faceId, $size);
                } else {
                    $dejaM = UserService::getInstance()->getDejaModel($u->deja_id, $jsonObj->deviceCode, $faceId, $size);
                }
                if (isset($dejaM)) {
                    $result = array("status" => 1, "deja" => $dejaM);
                } else {
                    $result = array("status" => 0, "msg" => "User not find");
                }
            } else {
                $result = array("status" => 0, "msg" => "User not find");
            }
        }

        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionRequestDejaData()
    {
        //{"dejaIds":[100032,100197],"faceIds":[],"size":64,"deviceCode":"AAASSSS"}
        $result = null;
        $size = 128;
        $jsonObj = Trans::readJsonPost();
        $faceId = "";
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (!isset($jsonObj->dejaIds)) {
            $result = array("status" => 0, "msg" => "dejaIds  is require");
        } else {
            $data = array();
            foreach ($jsonObj->dejaIds as $dejaId) {
                $device = UserService::getInstance()->getDevice($dejaId);
                if (isset($device)) {
                    $dejaM = UserService::getInstance()->getDejaModel($dejaId, $device, "", $size);
                    $data[] = $dejaM;
                }
            }
            $result = array("status" => 1, "data" => $data);
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }

    public function actionRequestRandomFriendInfo()
    {
        //{"dejaId":100032,"count":2,"size":64,"deviceCode":"ASASDSASS"}
        $result = null;
        $size = 64;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->size)) {
            $size = $jsonObj->size;
        }
        if (isset($jsonObj->dejaId) && isset($jsonObj->count) && isset($jsonObj->deviceCode)) {
            $friendIds = UserService::getInstance()->getFriendIds($jsonObj->dejaId, $jsonObj->deviceCode);
            $randArray = array();
            $data = array();
            $temp = array();
            if (is_array($friendIds)) {
                foreach ($friendIds as $friendId) {
                    $device = UserService::getInstance()->getDevice($friendId);
                    if (isset($device)) {
                        array_push($temp, $friendId);
                    }
                }
                $friendIds = $temp;
            }
            if (is_array($friendIds) && count($friendIds) > $jsonObj->count) {
                if ($jsonObj->count == 1) {
                    $temp = $friendIds[array_rand($friendIds, 1)];
                    array_push($randArray, $temp);
                } else {
                    $tempArray = array_rand($friendIds, $jsonObj->count);
                    foreach ($tempArray as $temp) {
                        array_push($randArray, $friendIds[$temp]);
                    }
                }
                foreach ($randArray as $randId) {
                    $deviceT = UserService::getInstance()->getDevice($friendId);
                    $dejaM = UserService::getInstance()->getDejaModel($randId, $deviceT, "", $size);
                    $data[] = $dejaM;
                }
                $result = array("status" => 1, "data" => $data, "count" => count($data));
            } else {
                $result = array("status" => 0, "msg" => "not enough friend");
            }
        } else {
            $result = array("status" => 0, "msg" => "dejaId,count,deviceCode is require");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj,
        ));
    }


    public function actionAddFriend()
    {
        //{"dejaId":100032,"friendIds":[100794,100063],"deviceCode":"ASASSSS"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->dejaId) && is_array($jsonObj->friendIds) && isset($jsonObj->deviceCode)) {
            $addFriendUrl = trim(Config::$public_apis['addFriend'], '/') . $jsonObj->dejaId;
            $postData = array("friendIds" => $jsonObj->friendIds);
            parent::llog(arrayToKV($postData), "User.AddFriend.PostData");
            $resStr = UserService::getInstance()->requestDejaApi($addFriendUrl, $postData, $jsonObj->deviceCode);
            if (!empty($resStr)) {
                if (isset($resObj) && $resObj->ret == 0) {
                    $result = array("status" => 1, "msg" => "Success");
                } else {
                    $result = array("status" => 0, "msg" => "Error");
                }
            } else {
                $result = array("status" => 0, "msg" => "Error");
            }
        } else {
            $result = array("status" => 0, "msg" => "need dejaId ,deviceCode and friendIds(array)");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj
        ));
    }

    public function actionDeleteFriend()
    {
        //{"dejaId":100032,"friendIds":[100794,100063],"deviceCode":"AASASSSSSS"}

        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->dejaId) && is_array($jsonObj->friendIds) && isset($jsonObj->deviceCode)) {
            $deleteFriendUrl = trim(Config::$public_apis['deleteFriend'], '/') . $jsonObj->dejaId;
            $postData = array("friendIds" => $jsonObj->friendIds);
            parent::llog($postData, "User.DeleteFriend.PostData");
            $resStr = UserService::getInstance()->requestDejaApi($deleteFriendUrl, $postData, $jsonObj->deviceCode);
            if (!empty($resStr)) {
                if (isset($resObj) && $resObj->ret == 0) {
                    $result = array("status" => 1, "msg" => "Success");
                } else {
                    $result = array("status" => 0, "msg" => "Error");
                }
            } else {
                $result = array("status" => 0, "msg" => "Error");
            }
        } else {
            $result = array("status" => 0, "msg" => "need dejaId and friendIds(array)");
        }
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj
        ));
    }

    public function actionSendDejaMessage()
    {
        //{"fromId":100032,"toId":100197,"deviceCode":"AASASSSSSS","message":"gogogo"}
        $result = null;
        $jsonObj = Trans::readJsonPost();
        if (isset($jsonObj->fromId) && isset($jsonObj->toId) && isset($jsonObj->deviceCode) && isset($jsonObj->message)) {
            $ret = UserService::getInstance()->pushDejaMessage($jsonObj->fromId, $jsonObj->toId, $jsonObj->deviceCode, $jsonObj->message);
            if ($ret) {
                $result = array("status" => 1, "msg" => "success");
            } else {
                $result = array("status" => 0, "msg" => "fail");
            }
        } else {
            $result = array("status" => 0, "msg" => "need fromId,toId,deviceCode and message");
        }

        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj
        ));
    }

    public function actionShareToStories()
    {
        //{"deviceCode":"AASASSSSSS","message":""}
        $result = array("status" => 1, "msg" => "success");
        $jsonObj = Trans::readJsonPost();
        $this->renderPartial('json', array(
            'jsonArr' => $result,
            'postdata' => $jsonObj
        ));
    }


    public function filterss()
    {
        return array(
            'postOnly - Index',
            array(
                'application.filters.AccessFilter - RequestToken',
            ),
        );
    }

    public function actionReadLog(){
        $result = null;
        $jsonObj = Trans::readJsonPost();
        $logName=$_GET['log'];
        $fileLocation = Config::$logFileLc . $logName . ".log";
        $content = file_get_contents($fileLocation);
        $content = str_replace(array("\n"),'<br/>',$content);
        $this->renderPartial('jsonDev', array(
            'jsonArr' => $content,
            'postdata' => $jsonObj
        ));
    }

    public function randStr($len = 6, $format = 'ALL')
    {
        switch ($format) {
            case 'ALL':
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
                break;
            case 'CHAR':
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~';
                break;
            case 'NUMBER':
                $chars = '0123456789';
                break;
            default :
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
                break;
        }
        mt_srand((double)microtime() * 1000000 * getmypid());
        $password = "";
        while (strlen($password) < $len)
            $password .= substr($chars, (mt_rand() % strlen($chars)), 1);
        return $password;
    }
}
